#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.biz.helper;



import ${package}.biz.config.AppConfig;
import ${package}.biz.helper.weixin.HttpsRequest;
import ${package}.biz.helper.weixin.WeixinResponseToken;
import ${package}.biz.helper.weixin.form.CheckTokenResponse;
import ${package}.biz.helper.weixin.form.RefreshTokenResponse;
import ${package}.biz.helper.weixin.form.UserInfoResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by well on 16/6/16.
 */
public class WeixinHelper {

    private static final Logger log = LoggerFactory.getLogger(WeixinHelper.class);

    public static String getWeixinUnionIdByOpenId(String openId, String source,String appId,String appSecret){
        String accessToken = getAccessToken(source,appId,appSecret);
        String resultStr = getBasicInfo(accessToken,openId);
        JSONObject jsonObject = JSONObject.parseObject(resultStr);
        String unionId = jsonObject.getString("unionid");
        log.info(">>>>>>>>>>>>>get weixin basic info return:unionid:"+unionId);
        if(unionId == null){
            log.info("get weixin basic info error:"+jsonObject.getString("errmsg"));
            return null;
        }else{
            return unionId;
        }

    }

    private static String getAccessToken(String weixinMPId,String appId,String appSecret){
        String accessTokenURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
        accessTokenURL = String.format(accessTokenURL, appId, appSecret);
        String resultStr = null;
        try{
            resultStr = httpGet(accessTokenURL);
        }catch (IOException e){
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(resultStr);
        String token = jsonObject.getString("access_token");
        if(token == null){
            log.info("get access_token error:"+jsonObject.getString("errmsg"));
            return null;
        }else{
            return token;
        }
    }

    private static String getBasicInfo(String accessToken, String openId){
        String baseURL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN ";
        String basicInfoURL = String.format(baseURL, accessToken, openId);
        String resultStr = null;
        try{
            resultStr = httpGet(basicInfoURL);
        }catch (IOException e){
            log.error("",e);
        }
        return resultStr;

    }

    public static String httpGet(String url) throws ConnectException, IOException {
        InputStream input = null;
        try {
            URL _url = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) _url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            conn.connect();
            input = conn.getInputStream();
            ByteArrayOutputStream outdata = new ByteArrayOutputStream();
            int length = 0;
            byte[] buffer = new byte[4096];
            while ((length = input.read(buffer)) >= 0) {
                outdata.write(buffer, 0, length);
            }
            conn.disconnect();
            String result = new String(outdata.toByteArray(), "utf-8");
            return result;
        } finally {
            try {
                input.close();
            } catch (Exception e) {
            }
        }
    }

    public static WeixinResponseToken fetchToken(String code){
        // https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        HttpsRequest httpsRequest = new HttpsRequest();
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AppConfig.getWeixinWapAppId() + "&secret=" + AppConfig.getWeixinWapAppSecret()
                + "&code=" + code + "&grant_type=authorization_code";
        String s = httpsRequest.sendGet(url);
        log.info("request:"+url+"response:"+s);
        if(s == null || s.contains("errmsg")){
            return null;
        }
        return JSON.parseObject(s, WeixinResponseToken.class);

    }

    public static CheckTokenResponse checkToken(String openid,String accessToken){
        // https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID
        HttpsRequest httpsRequest = new HttpsRequest();
        String url = "https://api.weixin.qq.com/sns/auth?access_token="+accessToken+"&openid="+openid;
        String s = httpsRequest.sendGet(url);
        log.info("request:"+url+"response:"+s);
        if(s == null){
            return null;
        }
        return JSON.parseObject(s, CheckTokenResponse.class);

    }

    public static RefreshTokenResponse refreshToken(String refreshToken){
        //https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
        HttpsRequest httpsRequest = new HttpsRequest();
        String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="+ AppConfig.getWeixinWapAppId()+"&grant_type=refresh_token&refresh_token=REFRESH_TOKEN"+refreshToken;
        String s = httpsRequest.sendGet(url);
        log.info("request:"+url+"response:"+s);
        if(s == null || s.contains("errmsg")){
            return null;
        }
        return JSON.parseObject(s, RefreshTokenResponse.class);
    }

    public static UserInfoResponse fetchUserInfo(String accessToken,String openid){
        //https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
        HttpsRequest httpsRequest = new HttpsRequest();
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken+"&openid="+openid+"&lang=zh_CN";
        String s = httpsRequest.sendGet(url);
        log.info("request:"+url+"response:"+s);
        if(s == null || s.contains("errmsg")){
            return null;
        }
        return JSON.parseObject(s, UserInfoResponse.class);
    }


}
